﻿var User = require("./User");
var gameDao = require("./../dao/gameDao");
var arithmetic = require("./arithmetic");
var sever = require("./sever");
var schedule = require("node-schedule");
var gameConfig = require("./../config/gameConfig");
var urlencode = require('urlencode');
var redis_send_and_listen = require("./../../util/redis_send_and_listen");
var log = require("./../../util/loginfo").getInstand;

var GameInfo = function () {

    var _gameinfo = "";

    var Game = function () {

        //初始化算法，使用第X种
        this.initAlgorithm = function (idx) {
            log.info('####init Algorithm!####')
            log.info('use [' + idx + '] Algorithm!')
            this.A = new arithmetic(idx);
        };

        this.serverId = gameConfig.serverId;

        //初始化游戏
        this.init = function () {
            log.info('####init game!####')

            //初始化算法
            this.initAlgorithm(0);
            //初始化用户列表
            this.userList = {};
            this.usergameList = {};
            //在线人数为0
            this.onlinePlayerCount = 0;
            //统计
            this.winTotal = 0;
            this.lotteryCount = 0;
            this.hourWinTotal = 0;
            this.hourlotteryCount = 0;
            this.times_id = 0;
            this.score_changeLogList = [];
            this.lotteryLogList = [];
            this.lineOutList = [];
            //维护模式
            this.maintain = false;

            this.sever = new sever();

            try {
                //查日志
                gameDao.selectGameLog((result) => {
                    if (result == 0) {
                        this.times_id = 10000001;
                    } else {
                        this.times_id = result[0].id + 1;
                    }
                    log.info("初始局号: " + this.times_id);
                });
            } catch (error) {
                log.err(error);
            }

            var rule = new schedule.RecurrenceRule();
            var times = [];
            for (var i = 0; i < 60; i++) {
                times.push(i);
            }
            rule.second = times;
            var c = 0;
            var self = this;
            var j = schedule.scheduleJob(rule, function () {
                if (gameConfig.maintain) {
                    --gameConfig.maintainTime;
                    //log.info(gameConfig.maintainTime);;
                    if (!gameConfig.maintainTime) {
                        self.disconnectAllUser();
                    }
                }

                self.score_changeLog();
                //self.lotteryLog();
                var nowDate = new Date();
                var minute = nowDate.getMinutes();
                var second = nowDate.getSeconds();
                if (minute % 10 == 0 && second == 1) {
                    //if (second == 1){
                    //	self.saveSocrePool();
                    self.saveGamblingBalanceGold();
                    log.info("保存库存和奖池");
                    redis_send_and_listen.send_msg("OnlineUserMsg",{server_id:gameConfig.serverId,online_num:self.onlinePlayerCount});
                    //log.info("推送在线人数");
                }

            });
        }

        this.tt = 0;

        this.lottery = function (_userId, _nBetList) {
            //用户_userid 摇奖
            //返回-1 未登录
            //返回-2 资金不足
            try {
                if (!_userId) {					//传输ID错误
                    log.info("未传用户ID");
                    return {code: -1};
                }
                if (!this.userList[_userId]) {	//未找到用户
                    log.info("找不到用户");
                    return {code: -1}
                }
                var init_coinConfig=gameConfig.coinConfig;
                if(init_coinConfig.indexOf(_nBetList)==-1){
                    log.info(_nBetList + "没有这个概率ID");
                    return {code: -1};
                }
    
                var score_before = this.userList[_userId].getScore();     //用户金币
                var sourceFreeCount = this.userList[_userId].getFreeCount();   //获取免费次数
                var youScore = this.userList[_userId].getScore();         //用户金币
                var GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
                //水位
                var nGamblingWaterLevelGold = GamblingBalanceLevelBigWin.nGamblingWaterLevelGold;
                //库存
                var nGamblingBalanceGold = GamblingBalanceLevelBigWin.nGamblingBalanceGold;
                //奖池
                var nGamblingWinPool = GamblingBalanceLevelBigWin.nGamblingWinPool;
                //大奖幸运等级
                var nGamblingBigWinLevel = GamblingBalanceLevelBigWin.nGamblingBigWinLevel;
                //大奖幸运概率
                var nGamblingBigWinLuck = GamblingBalanceLevelBigWin.nGamblingBigWinLuck;
    
                var is_luck=false;
    
                //判断幸运值
                var random_Num_1000=RandomNumBoth(0,1000);
                var random_Num_100=RandomNumBoth(0,100);
                if(nGamblingBigWinLevel[2]>=random_Num_1000){
                    if(nGamblingBigWinLuck[2]>=random_Num_100){
                        is_luck=true
                    }
                }else if(nGamblingBigWinLevel[1]>=random_Num_1000){
                    if(nGamblingBigWinLuck[1]>=random_Num_100){
                        is_luck=true
                    }
                }else if(nGamblingBigWinLevel[0]>=random_Num_1000){
                    if(nGamblingBigWinLuck[0]>=random_Num_100){
                        is_luck=true
                    }
                }
    
                //测试幸运值为true
                // is_luck=true
    
    
    
    
                var bFreeTimeFlag=false;     //是否有免费次数
                if(sourceFreeCount>0){
                    bFreeTimeFlag=true
                }
    
                //======================================================================================
                var nBetList=_nBetList;    //下注数组
                // 下注总额
                var nBetSum = _nBetList;
                var addBalanceGold=parseInt(nBetSum*parseInt(nGamblingWaterLevelGold)/100);    //进入库存的钱
                var addWinPool=parseInt(nBetSum-addBalanceGold);                     //进入奖池的钱
                var jackpotUpperLimit=0;
    
                //用户扣钱或者减少免费次数
                var lotteryResult = this.userList[_userId].lottery(nBetSum);
                if (!lotteryResult) {
                    log.info(_userId + "分数不够");
                    //log.info(this.userList[_userId])
                    return {code: -2}
                }
                if(!bFreeTimeFlag){
                    //增加库存和奖池
                    this.A.addGamblingBalanceGold(addBalanceGold,addWinPool);
                    jackpotUpperLimit=parseInt(nGamblingWinPool+addWinPool);   //可以赢的钱奖池加上下注进入奖池的钱
                }else {
                    jackpotUpperLimit=parseInt(nGamblingWinPool)
                }
    
                //发牌
    
    
                var card_list = JSON.parse(JSON.stringify(gameConfig.POKER));
                card_list.sort(randomsort);
                var zhuang_card=[card_list[0]];
                var hand_card=[card_list[1],card_list[2]];
                card_list.splice(0,3);
    
                var q_safe=false;    //是否询问买保险
                if(getNumber(zhuang_card[0])==1){
                    q_safe=true
                }
    
    
    
                var zhuang_num=[getNumber(zhuang_card[0])];
                var user_num=[getNumber(hand_card[0]),getNumber(hand_card[1])];
    
                var user_is_black=false;
                if(hand_card.length==2){
                    if((getNumber(hand_card[0])==1&&getNumber(hand_card[1])==10)||(getNumber(hand_card[1])==1&&getNumber(hand_card[0])==10 )){
                        user_is_black=true
                    }
                }
    
    
                var zhuang_is_black=false;
    
                var res_dict={
                    card_list:card_list, //剩余牌
                    zhuang_card:zhuang_card, //庄的牌
                    hand_card:hand_card, //手牌
                    bet_score:nBetSum, //下注数
                    is_safe:false, //是否买保险
                    safe_score:0, //保险数额   默认下注数一半
                    zhuang_num:zhuang_num, //庄点数  数组
                    user_num:user_num, //玩家点数    数组
                    zhuang_is_black:zhuang_is_black, //庄是否黑杰克
                    user_is_black:user_is_black, //玩家是否黑杰克
                    q_safe:q_safe, //是否询问用户买保险
                    is_over:false, //游戏是否结束
                    win_res:-1, //游戏结果
                };
    
                res_dict=this.A.check(res_dict); 
                var is_over=res_dict.is_over;
                this.usergameList[_userId]=res_dict;
                res_dict.code= 1;
    
                //log.info(res_dict);
                if(is_over){
                    log.info("下注后结束。。。");
                    res_dict = this.A.game_over(res_dict);
                    if(res_dict.win_score){
                        this.userList[_userId].winscore(res_dict.win_score)
                    }
    
                    //1.写记录
                    var userInfo = {
                        userid: _userId, 
                        bet: this.usergameList[_userId].bet_score, 
                        lines: 0,
                        score_before: 0, 
                        score_win: res_dict.win_score,
                        score_current: 0, 
                        result_array: JSON.stringify(res_dict),
                        score_linescore: res_dict.bet_score, 
                        free_count_win: 0, 
                        free_count_before: 0,
                        free_count_current: 0
                    }
                    this.lotteryLogList.push(userInfo);
                    log.info("userInfo == " + userInfo + " lottery log list " + JSON.stringify(this.lotteryLogList));
                    this.lotteryLog();
    
                    var CoinLog = [];
                    var logTemp = {
                        userId: parseInt(_userId),
                        useCoin: res_dict.bet_score,
                        winCoin: res_dict.win_score - res_dict.bet_score,
                        tax: 0,
                        serverId: gameConfig.serverId,
                        gameId: gameConfig.gameId,
                        round_no: this.times_id,
                        bet_list: "",
                        result: ""
                    }
                    CoinLog.push(logTemp);
                    log.info("lottery insert mark userId " + _userId + " bet score " + res_dict.bet_score + " round_no " + this.times_id);
                    this._Csocket.emit("insertMark", CoinLog);
    
                    var new_d = JSON.parse(JSON.stringify(res_dict));
                    new_d.user_score=this.userList[_userId]._score
    
                    this.usergameList[_userId]={};
    
                    //查日志
                    gameDao.selectGameLog((result) => {
                        this.times_id = result[0].id + 1;
                        log.info("开奖结束循环局号: " + this.times_id);
                    });
                    return new_d
                }else {
                    log.info("下注后返回。。。");
                    this.usergameList[_userId]=res_dict;
                    return res_dict;
                }
    
                //---------------------------------------------------------------------
                var ResultArray = dictAnalyseResult
                var winscore=parseInt(dictAnalyseResult["win"])+parseInt(dictAnalyseResult["getOpenBox"]["win"]);
    
                //减少奖池
                if(winscore>0){
                    this.A.subGamblingBalanceGold(0,winscore);
                }
    
                log.info("最大赢钱数",jackpotUpperLimit);
                log.info("库存",this.A.getGamblingBalanceLevelBigWin().nGamblingBalanceGold);
                log.info("奖池",this.A.getGamblingBalanceLevelBigWin().nGamblingWinPool);
                log.info("免费次数",this.userList[_userId].getFreeCount());
                log.info("用户赢钱数",winscore);
    
    
                var freeCount=dictAnalyseResult["getFreeTime"]["nFreeTime"]
    
                this.userList[_userId].winscore(winscore);
                this.userList[_userId].AddFreeCount(freeCount);
                var resFreeCount = this.userList[_userId].getFreeCount();
                var score_current = this.userList[_userId].getScore();
                var arstring = JSON.stringify(dictAnalyseResult);
                if(resFreeCount){
                    dictAnalyseResult["is_free"]=true
                }else {
                    dictAnalyseResult["is_free"]=false
                }
                dictAnalyseResult["user_score"]=this.userList[_userId].getScore();
    
    
                //写入服务器记录
                //1.写记录
                var userInfo = {
                    userid: _userId, bet: _bet, lines: 0,nBetSum:nBetSum,
                    score_before: score_before, score_win: winscore,
                    score_current: score_current, result_array: arstring,
                    score_linescore: nBetSum, free_count_win: freeCount, free_count_before: sourceFreeCount,
                    free_count_current: resFreeCount
                }
                this.lotteryLogList.push(userInfo);
    
                //记录金钱变化量
                var userInfolog = {
                    userid: _userId,
                    score_before: youScore,
                    score_change: winscore - nBetSum,
                    score_current: score_current,
                    change_type: gameConfig.logflag,
                    isOnline: true
                };
    
                this.score_changeLogList.push(userInfolog);
    
                //制作结果
                var Result = {
                    code: 1, userscore: score_current-dictAnalyseResult["getOpenBox"]["win"], winscore: dictAnalyseResult["win"],
                    viewarray: ResultArray, winfreeCount: freeCount,
                    freeCount: resFreeCount, score_pool: 0,
                    dictAnalyseResult: dictAnalyseResult
                }
    
                //服务器统计
                ++this.lotteryCount;
                ++this.hourlotteryCount;
                if (lotteryResult == 1) {
                    this.winTotal += (winscore - nBetSum);
                    this.hourWinTotal += (winscore - nBetSum);
                } else if (lotteryResult == 2) {
                    this.winTotal += winscore;
                    this.hourWinTotal += winscore;
                }
                //log.info(Result)
                return Result; 
            } catch (error) {
                log.err(error);
            }
        };

        this.send_card = function (_userId, is_fanbei,is_ting) {
            //补拍或者翻倍
            if(!this.usergameList[_userId]){
                log.info("没有用户usergameList数据:",_userId);
                return
            }
            var res_dict= this.usergameList[_userId];

            if(is_fanbei && res_dict.hand_card.length==2){
                //用户扣钱或者减少免费次数
                var lotteryResult = this.userList[_userId].lottery(this.usergameList[_userId].bet_score);
                if (!lotteryResult) {
                    log.info(_userId + "分数不够");
                    //log.info(this.userList[_userId])
                    return {code: -2}
                }
                res_dict.bet_score*=2;
                res_dict.is_fanbei =true
            }

            if(!is_ting){
                if (res_dict.hand_card !== undefined) {
                    res_dict.hand_card.push(res_dict.card_list[0]);
                }
                if (res_dict.user_num !== undefined) {
                    res_dict.user_num.push(getNumber(res_dict.card_list[0]));
                }
                res_dict.card_list.splice(0,1);

                if(res_dict.hand_card.length > 4){
                    is_ting=true;
                    res_dict=this.A.check(res_dict,is_fanbei,is_ting)
                }else {
                    res_dict=this.A.check(res_dict,is_fanbei);
                }
            }else {
                res_dict=this.A.check(res_dict,is_fanbei,is_ting);
            }

            var is_over=res_dict.is_over;
            //log.info(res_dict);

            if(is_over){
                log.info("发牌后结束。。。");
                res_dict = this.A.game_over(res_dict);
                if(res_dict.win_score){
                    this.userList[_userId].winscore(res_dict.win_score)
                }
                //1.写记录
                var userInfo = {
                    userid: _userId, 
                    bet: this.usergameList[_userId].bet_score, 
                    lines: 0,
                    score_before: 0, 
                    score_win: res_dict.win_score,
                    score_current: 0, 
                    result_array: JSON.stringify(res_dict),
                    score_linescore: res_dict.bet_score, 
                    free_count_win: 0, 
                    free_count_before: 0,
                    free_count_current: 0
                }
                this.lotteryLogList.push(userInfo);
                log.info("userInfo == " + userInfo + " lottery log list " + JSON.stringify(this.lotteryLogList));
                this.lotteryLog();

                var CoinLog = [];
                var logTemp = {
                    userId: parseInt(_userId),
                    useCoin: res_dict.bet_score,
                    winCoin: res_dict.win_score - res_dict.bet_score,
                    tax: 0,
                    serverId: gameConfig.serverId,
                    gameId: gameConfig.gameId,
                    round_no: this.times_id,
                    bet_list: "",
                    result: ""
                }
                CoinLog.push(logTemp);
                log.info("send card insert mark userId " + _userId + " bet score " + res_dict.bet_score + " round no " + logTemp.round_no);
                this._Csocket.emit("insertMark", CoinLog);

                var new_d = JSON.parse(JSON.stringify(res_dict));
                if (this.userList[_userId]._score) {
                    new_d.user_score=this.userList[_userId]._score;
                }
                this.usergameList[_userId]={};

                gameDao.selectGameLog((result) => {
                    if (result) {
                        this.times_id = result[0].id + 1;
                        log.info("开奖结束循环局号: " + this.times_id);
                    }
                });

                return new_d
            }else {
                log.info("发牌后返回。。。");
                return res_dict;
            }


        };





        this.setIo = function (_io, _Csocket) {
            this.sever.setIo(_io, _Csocket);
            this._io = _io;
            this._Csocket = _Csocket;
        }


        this.Setmaintain = function () {
            gameConfig.maintain = true;
        }

        this.isMaintain = function () {
            return gameConfig.maintain;
        }

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = function (socket) {
            if (socket.userId) {
                return this.userList[socket.userId].Islogin();
            }
            else {
                return false;
            }
        }

        //添加用户
        this.addUser = function (_userInfo, socket) {
            this.userList[_userInfo.userid] = new User(_userInfo, socket);
        }

        this.updateUser = function (userInfo) {
            log.info("update")
            if (!this.userList[userInfo._userId]) return;

            //已经断线
            if (this.userList[userInfo._userId]._isLeave) {
                var result = {ResultCode: 0, userId: userInfo._userId};
                this._Csocket.emit("userDisconnect", result);
                delete this.userList[userInfo._userId];
                return;
            }
            this.userList[userInfo._userId].update(userInfo);

            this.LoginGame(userInfo._userId, this.serverId);
            ++this.onlinePlayerCount;

            var self = this;
            var resultObj = {
                account: self.userList[userInfo._userId]._account,
                id: self.userList[userInfo._userId]._userId,
                nickname: self.userList[userInfo._userId]._nickname,
                score: self.userList[userInfo._userId]._score,
                headimgurl:self.userList[userInfo._userId]._headimgurl
            };
            result = {resultid: '1', msg: 'login lineserver succeed!', Obj: resultObj};

            this.userList[userInfo._userId]._socket.emit('loginGameResult', result);

        }

        //获得在线人数
        this.getOnlinePlayerCount = function () {
            return this.onlinePlayerCount;
        }

        //在线所有人
        this.getOnlinePlayer = function () {
            return this.userList;
        }

        this.score_changeLog = function () {
            var self = this;
            var saveListTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.score_changeLogList.length > 200) {
                max = 200;
            } else {
                max = this.score_changeLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.score_changeLogList.length > 0) {
                    ItemTemp = this.score_changeLogList.shift();
                    saveListTemp.push(ItemTemp);
                }
            }
            if (saveListTemp.length > 0) {
                this._Csocket.emit("score_changeLog", saveListTemp);
                //gameDao.score_changeLog(saveListTemp);
            }
        }

        this.lotteryLog = function () {
            try {
                var saveListLotteryLogTemp = [];
                var ItemTemp;
                var max = 0;
                if (this.lotteryLogList.length > 200) {
                    max = 200;
                } else {
                    max = this.lotteryLogList.length;
                }
                for (var i = 0; i < max; i++) {
                    if (this.lotteryLogList.length > 0) {
                        ItemTemp = this.lotteryLogList.shift();
                        saveListLotteryLogTemp.push(ItemTemp);
                        log.info("push ItemTemp == " + JSON.stringify(ItemTemp));
                        break;
                    }
                }
                if (saveListLotteryLogTemp.length > 0) {
                    log.info("lotteryLog saveListLotteryLogTemp  ");
                    gameDao.lotteryLog(saveListLotteryLogTemp);
                }
            } catch (error) {
                log.err(error);
            }
        }

        //删除用户
        this.deleteUser = function (_socket) {
            if (_socket.userId) {
                //存免费次数
                var info = {
                    userId: _socket.userId,
                    freeCount: this.userList[_socket.userId].getFreeCount(),
                    LotteryCount: this.userList[_socket.userId].getLotteryCount()
                };
                gameDao.saveFree(info, function (result) {
                    if (!result)
                    log.err("存免费次数:" + _userinfo.userId + "失败!")
                });
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    serverId: gameConfig.serverId,
                    userId: _socket.userId,
                    tableId: -1,
                    seatId: -1
                });
                this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
                delete this.userList[_socket.userId];
                --this.onlinePlayerCount;
            }
        }

        //删除用户
        this.deleteUserById = function (_userId, msg) {
            if (_userId) {
                var socketItem = this.userList[_userId]._socket;
                result = {resultid: 0, msg: msg};
                socketItem.emit('loginGameResult', result);
                delete this.userList[_userId];
            }
        }

        //获得用户当前分数
        this.getUserscore = function (_userId) {
            if (_userId) {
                return this.userList[_userId]._score;
            }
        }

        //获得用户
        this.getUser = function (_userId) {
            if (_userId) {
                return this.userList[_userId];
            }
        }

        //用户是否在线
        this.IsPlayerOnline = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询在线,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return 1;
            } else {
                return 0;
            }
        }

        //获得用户当前分数
        this.getPlayerScore = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询分数,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return this.userList[_userId].getScore();
            } else {
                return -1;
            }
        }

        //GM加分
        this.addgold = function (_userId, score) {

            if (!_userId) {					//传输ID错误
                log.info("加分,未登录")
                return 0;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("加分,未登录")
                return 0
            } else {
                log.info(score)
                if (this.userList[_userId].addgold(score)) {
                    log.info(this.userList[_userId].getScore())
                    log.info("加分成功!")
                    var tablestring = "table" + this.userList[_userId].getTable();
                    this._io.sockets.in(tablestring).emit('addgoldResult', {
                        userId: _userId,
                        userSeatId: this.userList[_userId].getSeat(),
                        userScore: this.userList[_userId]._score
                    })
                    return 1;
                } else {
                    log.info("减分失败,大于用户分数!");
                    return 0;
                }
            }
        }

        //保存时间段输赢状况
        this.saveSocrePool = function () {
            //获得虚拟池
            var Virtualpool = this.A.getVirtualScorePool();
            //获得实际池
            var poollist = this.A.getScorePoolList();

            //var poollistLength = this.A.getScorePoolListLength();

            var poollistId = this.A.getScoreId();

            gameDao.Update_score_pool(poollist, Virtualpool, poollistId, function (Result) {
            })
        }

        //保存库存 奖池
        this.saveGamblingBalanceGold = function () {
            //获得库存奖池
            var dict = this.A.getGamblingBalanceGold();

            gameDao.Update_GamblingBalanceGold(dict.nGamblingBalanceGold,dict.nGamblingWinPool, function (Result) {
            })
        }


        //进入游戏
        this.LoginGame = function (_userId, gametype) {
            if (!this.userList[_userId]) return;
            //用户添加游戏ID
            //log.info(_userId)
            //log.info("用户进入游戏" + gametype);
            this.userList[_userId].loginGame(gametype);
        }


        //进入房间
        this.LoginRoom = function (_userId, roomid, _socket) {
            if (!this.userList[_userId]) return;


            if (!this.userList[_userId].getGameId()) {
                log.info("用户" + _userId + ",没有进入任何游戏,进入房间")
                return;
            }

            if (this.userList[_userId].getSeat() != -1) {
                log.info("用户" + _userId + "已经有座位");
                return;
            }

            this.userList[_userId].loginRoom(roomid);
            var LoginResult;
            var linemsg = this.getLineOutMsg(_userId);
            if (linemsg.Result) {
                log.info("断线重连接table:" + linemsg.tableId + " seatid:" + linemsg.seatId);
                LoginResult = this.sever.LoginRoombyLineOut(this.getUser(_userId), _socket, linemsg.tableId, linemsg.seatId);
                this.lineOutSet({state: 0, userId: _userId});
            } else {
                LoginResult = this.sever.LoginRoom(this.getUser(_userId), _socket);
            }

            //发送场景消息
            //检查自己下注情况,效准玩家金额
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                //log.info("**" + Result.Id);
                if (!self.userList[_userId]) return;
                Result.Id=_userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);

                var ResultData = {
                    TableId: LoginResult.tableId,
                    seatId: LoginResult.seatId,
                    score_pool: 0
                }
                _socket.emit("LoginRoomResult", {ResultCode: 1, ResultData: ResultData});

            })

        }

        //登录获取免费次数
        this.LoginfreeCount=function(_userId,_socket){
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                if (!self.userList[_userId]) return;
                Result.Id=_userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);
                _socket.emit("LoginfreeCountResult", {ResultCode: 1, freeCount: Result.freeCount});
            })
        };


        //断线保存
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                this.lineOutList[_info.userId] = {tableId: _info.tableId, seatId: _info.seatId}
                //log.info(this.lineOutList[_info.userId]);
            } else {
                //移除
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: _info.userId
                })
                delete this.lineOutList[_info.userId];
            }
        }

        //获得断线用户信息
        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return {Result: 0};
            }
        }

        //清楚断线用户信息
        this.cleanLineOut = function () {
            //清理登录服务器
            log.info(this.lineOutList)
            for (var Item in this.lineOutList) {
                Item = parseInt(Item)
                var tableid = this.lineOutList[Item].tableId;
                var tablestring = "table" + tableid;
                this._io.sockets.in(tablestring).emit('PlayerOut', {
                    PlayerSeatId: this.lineOutList[Item].seatId,
                    userId: Item
                });
                this.sever.cleanLineOut(tableid, this.lineOutList[Item].seatId)
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: Item
                })
            }
            this.lineOutList = {};
        }

        this.getDownTime = function (_socket) {
            if (!this.userList[_socket.userId]) {
                //log.info("用户" + _socket.userId + "不存在");
                return;
            }

            var tableid = this.userList[_socket.userId].TableId;
            if (tableid < 0) {
                _socket.emit("getDownTimeResult", {ResultCode: 0, msg: "用户没有进入桌子"});
                return;
            }

            if (this.upUserList[tableid].length == 0) {
                _socket.emit("getDownTimeResult", {
                    ResultCode: 1,
                    downTime: this.sever.downTime,
                    upUserList: [],
                    upCoin: 0,
                    DownCoin: [0, 0, 0],
                    myDownCoin: [0, 0, 0]
                });
                return;
            }

            var down1 = 0;
            var down2 = 0;
            var down3 = 0;
            for (var itme in this.downCoinList[tableid]) {
                down1 += this.downCoinList[tableid][itme][0];
                down2 += this.downCoinList[tableid][itme][1];
                down3 += this.downCoinList[tableid][itme][2];
            }

            var mydown1 = 0;
            var mydown2 = 0;
            var mydown3 = 0;
            if (this.downCoinList[tableid][_socket.userId]) {
                mydown1 = this.downCoinList[tableid][_socket.userId][0];
                mydown2 = this.downCoinList[tableid][_socket.userId][1];
                mydown3 = this.downCoinList[tableid][_socket.userId][2];
            }

            //每门下注额度
            _socket.emit("getDownTimeResult", {
                ResultCode: 1,
                downTime: this.sever.downTime,
                upUserList: this.upUserList[tableid],
                upCoin: this.upUserList[tableid][0].upCoin,
                DownCoin: [down1, down2, down3],
                myDownCoin: [mydown1, mydown2, mydown3]
            });
        }


        this.disconnectAllUser = function () {
            for (var itme in this.userList) {
                this.userList[itme]._socket.disconnect();
            }
            log.info("服务器开启维护，已经全部离线");
        }

        //运行初始化
        this.init();
    }


    if (_gameinfo) {
        return {getInstand: _gameinfo}
    }
    else {
        log.info("####create game!####");
        _gameinfo = new Game();
        return {getInstand: _gameinfo}
    }

}()

function RandomNumBoth(Min, Max) {
    //生成指定范围内随机整数
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}

function RandomNumForList(arr) {
    //从指定数组中选取随机值
    return arr[Math.floor((Math.random() * arr.length))]

}

function getNumber(nCard) {
    //获取牌的牌数(扑克用)
    if (parseInt(parseInt(nCard / 16) / 16) > 9) {
        return 10
    } else {
        return parseInt(parseInt(nCard / 16) / 16)
    }

}

function randomsort(a, b) {
    //数组随机排序
    //使用方法
    //arr.sort(randomsort)
    return Math.random() > .5 ? -1 : 1; //通过随机产生0到1的数，然后判断是否大于0.5从而影响排序，产生随机性的效果。
}


module.exports = GameInfo;

